package myfirstgrailsproject

/**
 * This class is a data-holder - this is what 
 * we store in the database.
 * 
 * Enrollments are used to facilitate the many-to-many
 * relationship between Users and Courses.
 * 
 * @author zach
 *
 */
class Enrollment {

	User user;
	Course course;
	
	static constraints = {

	}

	//Used to enroll a user in a course
	static Enrollment link(user, course){
		def enrollment = Enrollment.findByUserAndCourse(user, course)
		if (!enrollment){
			enrollment = new Enrollment();
			user?.addToEnrollments(enrollment);
			course?.addToEnrollments(enrollment);
			enrollment.save();
		}
		return enrollment;
	}

	//Used to un-enroll a user from a course
	static void unlink(user, course){
		def enrollment = Enrollment.findByUserAndCourse(user, course);

		if (enrollment){
			user?.removeFromMemberships(enrollment);
			course?.removeFromMemberships(enrollment);
			enrollment.delete();
		}
	}


	String toString(){
		return "Course: " + course.title + ", Student: " + user.firstName + " " + user.lastName
	}

	static belongsTo = [Course, Team]
}
